<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2021/1/29
 * Time: 11:12
 */
namespace App\Api\Controllers\AlipayOpen;

use Alipayopen2019\AopClient;
use Alipayopen2019\request\AlipayMarketingUserulePidQueryRequest;
use Alipayopen2019\request\AlipayMarketingVoucherQueryRequest;
use Alipayopen2019\request\AlipayMarketingVoucherTemplatedetailQueryRequest;
use Alipayopen2019\request\AlipayMarketingVoucherTemplatelistQueryRequest;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CashlessVoucherController extends BaseController
{

    /**
     * 查询模板详情
     *
     * 包含准实时的汇总信息
     * @param Request $request
     * @return string
     */
    public function voucherTemplateDetailQuery(Request $request)
    {
        $store_id = $request->post('storeId', ''); //系统门店id
        $template_id = $request->post('templateId', ''); //券模板ID

        if (!isset($store_id) && empty($store_id)) {
            return json_encode([
                'status' => 2,
                'message' => '门店id,为必传参数'
            ]);
        }

        if (!isset($template_id) && empty($template_id)) {
            return json_encode([
                'status' => 2,
                'message' => '券模板ID,为必传参数'
            ]);
        }

        $storeObj = Store::where('store_id', $store_id)
            ->where('is_close', 0)
            ->where('is_delete', 0)
            ->first();
        if (!$storeObj) {
            return json_encode([
                'status' => 2,
                'message' => '门店不存在或状态异常,请联系管理员'
            ]);
        }

        $config = $storeObj->config_id;

        $AlipayIsvConfigObj = $this->isv_config($config);
        if (!$AlipayIsvConfigObj) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->app_id) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝应用ID,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->rsa_private_key) {
            return json_encode([
                'status' => 2,
                'message' => '开发者私钥,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->alipay_rsa_public_key) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝公钥,未配置'
            ]);
        }

        $app_id = $AlipayIsvConfigObj->app_id;
        $rsa_private_key = $AlipayIsvConfigObj->rsa_private_key;
        $alipay_rsa_public_key = $AlipayIsvConfigObj->alipay_rsa_public_key;

        $requestData = "{" .
            "\"template_id\":\"$template_id\"" .
            "  }";
        try {
            $aop = new AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $app_id; //支付宝分配给开发者的应用ID
            $aop->rsaPrivateKey = $rsa_private_key; //开发者私钥去头去尾去回车，一行字符串
            $aop->alipayrsaPublicKey = $alipay_rsa_public_key; //支付宝公钥，一行字符串
            $aop->apiVersion = '1.0'; //调用的接口版本，固定为：1.0
            $aop->signType = 'RSA2'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->postCharset = 'UTF-8'; //请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->format = 'json'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $request = new AlipayMarketingVoucherTemplatedetailQueryRequest();
            $request->setBizContent($requestData);
            $result = $aop->execute ( $request);
            Log::info('查询模板详情-返回');
            Log::info($result);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return json_encode([
                    'status' => 1,
                    'message' => isset($result->$responseNode->msg) ? $result->$responseNode->msg: '成功',
                    'data' => [
                        'template_id' => $result->$responseNode->template_id, //券模板ID
                        'voucher_type' => $result->$responseNode->voucher_type, //券类型。可枚举，暂时只支持代金券(FIX_VOUCHER)、无资金单品代金券（ITEM_CASHLESS_FIX_VOUCHER）、无资金单品折扣券（ITEM_CASHLESS_DISCOUNT_VOUCHER）、无资金单品特价券（ITEM_CASHLESS_SPE_VOUCHER）
                        'voucher_name' => $result->$responseNode->voucher_name, //券名称
                        'publish_start_time' => $result->$responseNode->publish_start_time, //发放开始时间，格式为：2017-01-01 00:00:01
                        'publish_end_time' => $result->$responseNode->publish_end_time, //发放结束时间，格式为：2017-01-29 23:59:59
                        'status' => $result->$responseNode->status, //模板状态，可枚举。分别为‘草稿’(I)、‘生效’(S)、‘删除’(D)和‘过期’(E)
                        'voucher_valid_period' => $result->$responseNode->voucher_valid_period, //json,券有效期。有两种类型：绝对时间和相对时间。绝对时间有3个key：type、start、end，type取值固定为"ABSOLUTE"，start和end分别表示券生效时间和失效时间，格式为yyyy-MM-dd HH:mm:ss。绝对时间示例：{"type": "ABSOLUTE", "start": "2017-01-10 00:00:00", "end": "2017-01-13 23:59:59"}。相对时间有3个key：type、duration、unit，type取值固定为"RELATIVE"，duration表示从发券时间开始到往后推duration个单位时间为止作为券的使用有效期，unit表示有效时间单位，有效时间单位可枚举：MINUTE, HOUR, DAY。示例：{"type": "RELATIVE", "duration": 1 , "unit": "DAY" }，如果此刻发券，那么该券从现在开始生效1(duration)天(unit)后失效
                        'floor_amount' => $result->$responseNode->floor_amount, //最低额度。券的最低使用门槛金额，只有订单金额大于等于最低额度时券才能使用。币种为人民币，单位为元。该数值不小于0，小数点以后最多保留两位。
                        'voucher_description' => $result->$responseNode->voucher_description, //券使用说明
                        'amount' => $result->$responseNode->amount, //面额。每张代金券可以抵扣的金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
                        'voucher_quantity' => $result->$responseNode->voucher_quantity, //拟发行券的数量。单位为张。该数值是大于0的整数
                        'total_amount' => $result->$responseNode->total_amount, //总金额面额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位。仅代金券有效。当券类型为无资金单品券（ITEM_CASHLESS_FIX_VOUCHER、ITEM_CASHLESS_DISCOUNT_VOUCHER、ITEM_CASHLESS_SPE_VOUCHER）时，暂不支持查询本参数，出参为0
                        'publish_count' => $result->$responseNode->publish_count, //已发放张数。单位为张。该数值是大于0的整数
                        'publish_amount' => $result->$responseNode->publish_amount, //已发放总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                        'used_count' => $result->$responseNode->used_count, //已使用张数。单位为张。该数值是大于0的整数
                        'used_amount' => $result->$responseNode->used_amount, //已使用总金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                        'recycle_amount' => isset($result->$responseNode->recycle_amount) ? $result->$responseNode->recycle_amount : 0 //选填,退回金额。币种为人民币，单位为元。该数值不小于0，小数点以后最多两位
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => isset($result->$responseNode->sub_msg) ? $result->$responseNode->sub_msg : '系统繁忙,请稍候再试'
                ]);
            }

        } catch (\Exception $ex) {
            Log::info('查询模板详情-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => '系统繁忙,请稍候再试'
            ]);
        }
    }


    /**
     * 查询券模板列表
     *
     * 分页查询当前PID下的所有模板
     * @param Request $request
     * @return string
     */
    public function voucherTemplateListQuery(Request $request)
    {
        $store_id = $request->post('storeId', ''); //系统门店id
        $create_start_time = $request->post('createStartTime', date('Y-m-d H:i:s', time())); //查询开始时间。即查询此时开始至 create_en_time 间创建的模板，格式为：2017-01-01 00:00:01
        $create_end_time = $request->post('createEndTime', date('Y-m-d 23:59:59', time())); //查询结束时间。即查询create_start_time至此时间创建的模板，格式为：2017-01-29 23:59:59
        $page_num = $request->post('pageNum', 1); //页码，必须为大于0的整数， 1表示第一页，2表示第2页，依次类推
        $page_size = $request->post('pageSize', 15); //每页记录条数，必须为大于0的整数，最大值为30

        if (!isset($store_id) && empty($store_id)) {
            return json_encode([
                'status' => 2,
                'message' => '门店id,为必传参数'
            ]);
        }

        $storeObj = Store::where('store_id', $store_id)
            ->where('is_close', 0)
            ->where('is_delete', 0)
            ->first();
        if (!$storeObj) {
            return json_encode([
                'status' => 2,
                'message' => '门店不存在或状态异常,请联系管理员'
            ]);
        }

        $config = $storeObj->config_id;

        $AlipayIsvConfigObj = $this->isv_config($config);
        if (!$AlipayIsvConfigObj) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->app_id) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝应用ID,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->rsa_private_key) {
            return json_encode([
                'status' => 2,
                'message' => '开发者私钥,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->alipay_rsa_public_key) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝公钥,未配置'
            ]);
        }

        $app_id = $AlipayIsvConfigObj->app_id;
        $rsa_private_key = $AlipayIsvConfigObj->rsa_private_key;
        $alipay_rsa_public_key = $AlipayIsvConfigObj->alipay_rsa_public_key;

        $requestData = "{" .
            "\"create_start_time\":\"$create_start_time\"," .
            "\"create_end_time\":\"$create_end_time\"," .
            "\"page_num\":$page_num," .
            "\"page_size\":$page_size" .
            "  }";

        try {
            $aop = new AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $app_id; //支付宝分配给开发者的应用ID
            $aop->rsaPrivateKey = $rsa_private_key; //开发者私钥去头去尾去回车，一行字符串
            $aop->alipayrsaPublicKey = $alipay_rsa_public_key; //支付宝公钥，一行字符串
            $aop->apiVersion = '1.0'; //调用的接口版本，固定为：1.0
            $aop->signType = 'RSA2'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->postCharset = 'UTF-8'; //请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->format = 'json'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $request = new AlipayMarketingVoucherTemplatelistQueryRequest();
            $request->setBizContent($requestData);
            $result = $aop->execute($request);
            Log::info('分页查询当前PID下的所有模板-返回');
            Log::info($result);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                //voucher_templates券模板列表的一个详情
                //template_id	//String,必填,32,券模板ID
                //voucher_name	//String,必填,32,券名称
                //publish_start_time	//必填,19,券模板发放开始时间。格式为：2017-01-01 00:00:01
                //publish_end_time	//必填,19,发放结束时间。格式为：2017-01-29 23:59:59
                //status	//String,必填,1,	模板状态，可枚举。分别为‘草稿’(I)、‘生效’(S)和‘过期’(E)
                //create_time	//必填,19,模板创建时间。格式为：2017-01-29 23:59:59
                //activate_time	//特殊可选,19,模板激活时间。草稿状态的模板该项为空 2017-01-01-12:00:00
                return json_encode([
                    'status' => 1,
                    'message' => '成功',
                    'data' => [
                        'total_pages' => $result->$responseNode->total_pages, //总页数
                        'current_page' => $result->$responseNode->current_page, //当前页码,页码从1开始
                        'items_per_page' => $result->$responseNode->items_per_page, //每页条数
                        'total_items' => $result->$responseNode->total_items, //总条数
                        'voucher_templates' => isset($result->$responseNode->voucher_templates) ? $result->$responseNode->voucher_templates : [] //选填,券模板列表
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => isset($result->$responseNode->sub_msg) ? $result->$responseNode->sub_msg : '系统繁忙,请稍候再试'
                ]);
            }

        } catch (\Exception $ex) {
            Log::info('分页查询当前PID下的所有模板-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => '系统繁忙,请稍候再试'
            ]);
        }
    }


    /**
     * 券查询
     *
     * 商户券信息查询
     * @param Request $request
     * @return string
     */
    public function voucherQuery(Request $request)
    {
        $store_id = $request->post('storeId', ''); //系统门店id
        $voucher_id = $request->post('voucherId', ''); //券ID(券唯一标识,,发券接口返回参数)

        if (!isset($store_id) && empty($store_id)) {
            return json_encode([
                'status' => 2,
                'message' => '门店id,为必传参数'
            ]);
        }

        if (!isset($voucher_id) && empty($voucher_id)) {
            return json_encode([
                'status' => 2,
                'message' => '券ID,为必传参数'
            ]);
        }

        $storeObj = Store::where('store_id', $store_id)
            ->where('is_close', 0)
            ->where('is_delete', 0)
            ->first();
        if (!$storeObj) {
            return json_encode([
                'status' => 2,
                'message' => '门店不存在或状态异常,请联系管理员'
            ]);
        }

        $config = $storeObj->config_id;

        $AlipayIsvConfigObj = $this->isv_config($config);
        if (!$AlipayIsvConfigObj) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->app_id) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝应用ID,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->rsa_private_key) {
            return json_encode([
                'status' => 2,
                'message' => '开发者私钥,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->alipay_rsa_public_key) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝公钥,未配置'
            ]);
        }

        $app_id = $AlipayIsvConfigObj->app_id;
        $rsa_private_key = $AlipayIsvConfigObj->rsa_private_key;
        $alipay_rsa_public_key = $AlipayIsvConfigObj->alipay_rsa_public_key;

        $requestData = "{" .
            "\"voucher_id\":\"$voucher_id\"" .
            "  }";
        try {
            $aop = new AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $app_id; //支付宝分配给开发者的应用ID
            $aop->rsaPrivateKey = $rsa_private_key; //开发者私钥去头去尾去回车，一行字符串
            $aop->alipayrsaPublicKey = $alipay_rsa_public_key; //支付宝公钥，一行字符串
            $aop->apiVersion = '1.0'; //调用的接口版本，固定为：1.0
            $aop->signType = 'RSA2'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->postCharset = 'UTF-8'; //请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->format = 'json'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $request = new AlipayMarketingVoucherQueryRequest();
            $request->setBizContent($requestData);
            $result = $aop->execute($request);
            Log::info('商户券信息查询-返回');
            Log::info($result);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                //bill_details中的一个账单信息
                //trade_no	//String,可选,64,支付宝交易号
                //amount	//必填,13,券核销/退款金额(元)	1.00
                //status	//String,必填,16,交易状态(I: 处理中, S: 成功)
                //partner_id	//String,可选,32,交易合作伙伴ID
                //partner_name	//String,可选,32,商户名称
                //biz_type	//String,必填,32,账单类型(V_USE:支付,V_REFUND:退款)
                //gmt_create	//必填,交易时间 2015-04-02 13:32:43
                return json_encode([
                    'status' => 1,
                    'message' => '成功',
                    'data' => [
                        'name' => $result->$responseNode->name, //券名称(用户看到券名称)
                        'voucher_id' => $result->$responseNode->voucher_id, //券ID(同入参券ID)
                        'user_id' => $result->$responseNode->user_id, //券所属用户ID
                        'template_id' => $result->$responseNode->template_id, //券模板ID(模板唯一标识,创建模板返回)
                        'gmt_active' => $result->$responseNode->gmt_active, //券激活时间(券可以使用起始时间)2015-04-02 13:32:43
                        'gmt_expired' => $result->$responseNode->gmt_expired, //券过期时间(券可以使用截止时间)2015-04-02 13:32:43
                        'total_amount' => $result->$responseNode->total_amount, //券面额(元)	1.00
                        'available_amount' => $result->$responseNode->available_amount, //券余额(元)	1.00
                        'status' => $result->$responseNode->status, //券状态(ENABLED:可用,DISABLED:不可用,DELETE:删除状态,TRANS:发放中,TRANSFER:已转增,UNC:未领取,USED:已使用,USING:使用中,REFUNDED:已退款,REFUNDING:退款中,UNACTIVE:未激活,EXPIRED:已过期)
                        'gmt_create' => $result->$responseNode->gmt_create, //券创建时间(即发券时间)	2015-04-02 13:32:43
                        'extend_info' => $result->$responseNode->extend_info, //扩展信息,JSON格式
                        'bill_details' => isset($result->$responseNode->bill_details) ? $result->$responseNode->bill_details : [] //选填,券交易账单信息(核销交易信息、交易退款信息等可能存在多条)
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => isset($result->$responseNode->sub_msg) ? $result->$responseNode->sub_msg : '系统繁忙,请稍候再试'
                ]);
            }

        } catch (\Exception $ex) {
            Log::info('商户券信息查询-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => '系统繁忙,请稍候再试'
            ]);
        }
    }


    /**
     * 商户使用场景规则PID查询
     *
     * 查询商户可用于使用场景规则的PID
     * @param Request $request
     * @return string
     */
    public function useRulePidQuery(Request $request)
    {
        $store_id = $request->post('storeId', ''); //系统门店id
        $pid = $request->post('pid', ''); //合作伙伴ID,传入ID比如与当前APPID所属合作伙伴ID一致,否则会报权限不足

        if (!isset($store_id) && empty($store_id)) {
            return json_encode([
                'status' => 2,
                'message' => '门店id,为必传参数'
            ]);
        }

        if (!isset($pid) && empty($pid)) {
            return json_encode([
                'status' => 2,
                'message' => '合作伙伴ID,为必传参数'
            ]);
        }

        $storeObj = Store::where('store_id', $store_id)
            ->where('is_close', 0)
            ->where('is_delete', 0)
            ->first();
        if (!$storeObj) {
            return json_encode([
                'status' => 2,
                'message' => '门店不存在或状态异常,请联系管理员'
            ]);
        }

        $config = $storeObj->config_id;

        $AlipayIsvConfigObj = $this->isv_config($config);
        if (!$AlipayIsvConfigObj) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->app_id) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝应用ID,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->rsa_private_key) {
            return json_encode([
                'status' => 2,
                'message' => '开发者私钥,未配置'
            ]);
        }
        if (!$AlipayIsvConfigObj->alipay_rsa_public_key) {
            return json_encode([
                'status' => 2,
                'message' => '支付宝公钥,未配置'
            ]);
        }

        $app_id = $AlipayIsvConfigObj->app_id;
        $rsa_private_key = $AlipayIsvConfigObj->rsa_private_key;
        $alipay_rsa_public_key = $AlipayIsvConfigObj->alipay_rsa_public_key;

        $requestData = "{" .
            "\"pid\":\"$pid\"" .
            "}";
        try {
            $aop = new AopClient();
            $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
            $aop->appId = $app_id; //支付宝分配给开发者的应用ID
            $aop->rsaPrivateKey = $rsa_private_key; //开发者私钥去头去尾去回车，一行字符串
            $aop->alipayrsaPublicKey = $alipay_rsa_public_key; //支付宝公钥，一行字符串
            $aop->apiVersion = '1.0'; //调用的接口版本，固定为：1.0
            $aop->signType = 'RSA2'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $aop->postCharset = 'UTF-8'; //请求使用的编码格式，如utf-8,gbk,gb2312等
            $aop->format = 'json'; //商户生成签名字符串所使用的签名算法类型，目前支持RSA2和RSA，推荐使用RSA2
            $request = new AlipayMarketingUserulePidQueryRequest();
            $request->setBizContent($requestData);
            $result = $aop->execute ( $request);
            Log::info('查询商户可用于使用场景规则的PID-返回');
            Log::info($result);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if (!empty($resultCode) && $resultCode == 10000) {
                return json_encode([
                    'status' => 1,
                    'message' => isset($result->$responseNode->msg) ? $result->$responseNode->msg: '成功',
                    'data' => [
                        'pids' => $result->$responseNode->pids
                    ]
                ]);
            } else {
                return json_encode([
                    'status' => 2,
                    'message' => isset($result->$responseNode->sub_msg) ? $result->$responseNode->sub_msg : '系统繁忙,请稍候再试'
                ]);
            }

        } catch (\Exception $ex) {
            Log::info('查询商户可用于使用场景规则的PID-error');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
            return json_encode([
                'status' => -1,
                'message' => '系统繁忙,请稍候再试'
            ]);
        }
    }


}
